import datetime

from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from web import models


class Tracer(object):
    def __init__(self):
        self.user = None  # 存储用户
        self.price_policy = None  # 存储用户的额度
        self.project = None # 封装当前的项目 当前项目的对象


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """如果用户已登录 则在rqeuest中赋值"""
        request.tracer = Tracer()

        username = request.session.get('user', 0)
        uesr_object = models.UserInfo.objects.filter(username=username).first()
        # print(uesr_object.username)  # 获取到的是name名字
        request.tracer.user = uesr_object

        # 获取当前访问的url  并判断是否登陆成功才能访问
        path = request.path_info
        # 创建一个白名单
        url_list = ['/index/', '/login/', '/img_code/', '/register/']

        # if not request.session.get('user') and path not in url_list:
        #     return redirect('/login')

        # 老师的写法
        if path in url_list:
            return
        # 检查用户是否已经登陆，已登录继续往后走
        if not request.tracer.user:
            return redirect('/login')

        # 登录成功后 访问后台管理时：获取当前用户所拥有的额度
        # 免费额度在交易记录中存储
        # 获取当前用户ID值最大（也就是最近一次的交易记录）
        _object = models.Transaction.objects.filter(user=uesr_object, status=2).order_by('-id').first()
        # 判断是否存在 且 过期
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=uesr_object, status=2, price_policy__category=1).first()
        # 存储了当前登录的用户额度信息
        request.tracer.price_policy = _object.price_policy


    def process_view(self, request, view, args, kwargs):
        # 判断url是否是/manage/开头 如果是的话进入 否则重定向
        # 如果是的话判断是否是我创建的或者是我参与的
        if not request.path_info.startswith('/manage/'):
            return
        # 获取url的project_id
        project_id = kwargs.get('project_id')
        # 判断是否是我创建的
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            request.tracer.project = project_object
            return
        # 判断是否是我参与的
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).filter()
        if project_user_object:
            request.tracer.project = project_user_object.project
            return
        return redirect('/project/list')

